<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="12">
            <a-form-item label="订单号">
              <a-input placeholder="输入订单号" v-model.trim="queryParam.customerOrderNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="物流产品">
              <j-search-select-tag placeholder="请选择物流产品" :getPopupContainer="null" v-model="queryParam.productId" dict="hz_logistics_product,name,id,logistics"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="运单号">
              <a-input placeholder="输入运单号" v-model.trim="queryParam.waybillNo"></a-input>
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="12">
            <a-form-item label="是否异常">
              <j-dict-select-tag placeholder="是否异常" v-model="queryParam.isAbnormal" dictCode="y_n"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="创建时间">
              <a-range-picker v-model="queryParamOther.createTimeRange" :default-value="[queryParam.createTime_begin, queryParam.createTime_end]"   @change="effectCreateTimeChange"  show-time style="width: 100%" valueFormat="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :md="6" :sm="12">
              <a-form-item label="对账时间">
                <a-range-picker v-model="queryParamOther.reconciliationTimeRange" @change="reconciliationTimeChange" show-time style="width: 100%" valueFormat="YYYY-MM-DD HH:mm:ss" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="国家/地区">
                <j-search-select-tag placeholder="请选择国家/地区" v-model="queryParam.countryCode" dict="hz_logistics_country_default,cn_name,code,logistics"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="结算状态">
                <j-dict-select-tag placeholder="请选择结算状态" v-model="queryParam.settleStatus" dictCode="logistics_settlement_status"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="结算组织">
                <j-dict-select-tag placeholder="请选择结算组织" v-model="queryParam.sysOrgCode" dict="sys_depart,full_name,org_code,org_category=1,system"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="出账状态">
                <j-dict-select-tag placeholder="请选择出账状态" v-model="queryParam.disburseStatus" dictCode="logistics_disburse_status"/>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="12">
              <a-form-item label="创建人">
                <a-input placeholder="输入创建人" v-model.trim="queryParam.createBy"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12" style="margin-bottom: 40px;">
              <a-form-item label="批量单号查询">
                <a-textarea :rows="3" v-model.trim="queryParam.orderNos" placeholder="输入批量单号查询" />
              </a-form-item>
            </a-col>
          </template>

          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset_" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls('物流运单')">导出运单</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('账单模板',url.downloadBillTemplate)">下载账单模板</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importBill" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入账单</a-button>
      </a-upload>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <!-- tab分栏 -->
      <a-row :gutter="24">
        <a-col :md="20" :sm="20">
          <table-sort class="table-sort" :sortList="sortList" :key="keyNumber" @changeTab="changeTab" />
        </a-col>
        <a-col :md="4" :sm="4">
          <div class="table-operator" style="margin-top: 17px;">
            <a-radio :checked="checked" @click="handleChecked">仅看与我相关运单</a-radio>
          </div>
        </a-col>
      </a-row>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange"
        :customRow="selectRowData">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;" :preview="0"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <!-- 物流信息 -->
        <template slot="remarkSlot" slot-scope="text, record">
          <j-ellipsis :value="text" :length="20" :style="{color: record.waybillStatus === '7' ? 'red' : '#797979'}"></j-ellipsis>
        </template>

        <!-- 运单号 -->
        <template slot="waybillNoSlot" slot-scope="text, record">
          <div class="waybill">
            <span style="color: #1890FF; cursor: pointer;" @click="handleTrajectory(record)">{{ text }}</span>
            <div class="trajectory" v-if="record.id === currentId">
              <div v-for="(item, index) in logisticsTrajectory" :key="index">
                <div class="time">{{ item.processTime && moment(item.processTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
                <div class="info">{{ item.trackNodeDesc }}  {{ item.processContent }}  </div>
              </div>
            </div>
          </div>
        </template>

        <!-- 预计运费相关 -->
        <template slot="expectFeeSlot" slot-scope="text,record">
          <div class="templateSlot">
            <div v-if="record.selfTestWeight">
              <span>重量：{{record.selfTestWeight}} KG</span>
            </div>
            <div v-if="record.estimateCost">
              <span>运费：{{record.estimateCost}} RMB</span>
            </div>
          </div>
        </template>

        <!-- 实际对账运费相关 -->
        <template slot="actualFeeSlot" slot-scope="text,record">
          <div class="templateSlot">
            <div v-if="record.actualWeight">
              <span>重量：{{record.actualWeight}} KG</span>
            </div>
            <div v-if="record.actualCost">
              <span>运费：{{record.actualCost}} RMB</span>
            </div>
          </div>
        </template>
        <!-- 成本效益相关 -->
        <template slot="costFeeSlot" slot-scope="text,record">
          <div class="templateSlot">
            <div v-if="record.disburseCost">
              <span>成本：{{record.disburseCost}} RMB</span>
            </div>
            <div v-if="record.disburseCost">
              <span>收益：{{record.profit}} RMB</span><span v-if="record.profit < 0" style="color: red;">（异常）</span>
            </div>
          </div>
        </template>

        <!-- 时间 -->
        <template slot="timeSlot" slot-scope="text,record">
          <div class="templateSlot">
            <div v-if="record.createTime">
              <span>创建：{{record.createTime}}</span>
            </div>
            <div v-if="record.reconciliationTime">
              <span>对账：{{record.reconciliationTime}}</span>
            </div>
          </div>
        </template>

        <!-- 运单状态 -->
        <template slot="waybillStatusSlot" slot-scope="text,record">
          <span :style="getColor(record)">{{ text }}</span>
        </template>

        <!-- 结算状态 -->
        <template slot="settleStatusSlot" slot-scope="text,record">
          <span :style="getColor_(record)">{{ text }}</span>
        </template>

        <!-- 出账标记 -->
        <template slot="disburseStatusSlot" slot-scope="text,record">
          <span :style="{color: record.disburseStatus === '1' ? '#fb7503' : '#1890FF'}">{{ text }}</span>
        </template>

        <span slot="action" slot-scope="text, record">
                <a @click="handleDetail(record)">详情</a>
                <a><j-operate-log :id="record.id"></j-operate-log></a>
        </span>

      </a-table>
    </div>

    <logistics-waybill-detail-modal ref="modalForm" @ok="modalFormOk"/>
  </a-card>
</template>

<script>
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import LogisticsWaybillDetailModal from '@views/logistics/waybill/modules/LogisticsWaybillDetailModal.vue'
  import TableSort from '@/components/table/TableSort'
  import { getAction } from '@/api/manage';
  import moment from 'moment';
  export default {
    name: 'LogisticsWaybillList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      LogisticsWaybillDetailModal,
      TableSort
    },
    data () {
      return {
        description: '物流运单管理页面',
        queryParam: {
          createTime_begin: moment(moment().subtract(1, 'month').startOf('day')).format('YYYY-MM-DD HH:mm:ss'),
          createTime_end: moment(moment().endOf('day')).format('YYYY-MM-DD HH:mm:ss')
        },
        queryParamOther: {},
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'客户单号',
            align:"center",
            dataIndex: 'customerOrderNo'
          },
          {
            title:'结算组织',
            align:"center",
            dataIndex: 'sysOrgCode_dictText'
          },
          {
            title:'物流产品',
            align:"center",
            dataIndex: 'productId_dictText'
          },
          {
            title:'运单号',
            align:"center",
            dataIndex: 'waybillNo',
            scopedSlots: { customRender: 'waybillNoSlot' }
          },
          {
            title:'国家/地区',
            align:"center",
            dataIndex: 'countryCode_dictText'
          },
          {
            title:'预报',
            align:"center",
            dataIndex: '',
            scopedSlots: { customRender: 'expectFeeSlot' }
          },
          {
            title:'对账',
            align:"center",
            dataIndex: '',
            scopedSlots: { customRender: 'actualFeeSlot' }
          },
          {
            title:'成本效益',
            align:"center",
            dataIndex: '',
            scopedSlots: { customRender: 'costFeeSlot' }
          },
          {
            title:'订单时间',
            align:"center",
            dataIndex: '',
            scopedSlots: { customRender: 'timeSlot' }
          },
          {
            title:'订单状态',
            align:"center",
            dataIndex: 'waybillStatus_dictText',
            scopedSlots: { customRender: 'waybillStatusSlot' }
          },
          {
            title:'出账状态',
            align:"center",
            dataIndex: 'disburseStatus_dictText',
            scopedSlots: { customRender: 'disburseStatusSlot' }
          },
          {
            title:'结算状态',
            align:"center",
            dataIndex: 'settleStatus_dictText',
            scopedSlots: { customRender: 'settleStatusSlot' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/logistics/waybill/logisticsWaybill/summaryList",
          delete: "/logistics/waybill/logisticsWaybill/delete",
          deleteBatch: "/logistics/waybill/logisticsWaybill/deleteBatch",
          exportXlsUrl: "/logistics/waybill/logisticsWaybill/exportSummaryXls",
          queryTrackInfo: "/logistics/waybill/logisticsWaybill/queryTrackInfo",
          queryWaybillGroupCount: "/logistics/waybill/logisticsWaybill/queryWaybillGroupCount",
          downloadTemplate: "/logistics/waybill/logisticsWaybill/downloadTemplate",
          downloadBillTemplate: "/logistics/waybill/logisticsWaybill/downloadBillTemplate",
          importBill: "logistics/waybill/logisticsWaybill/importBill"
        },
        // superFieldList:[],
        sortList: [
          {
            text: '全部',
            value: '',
            countText: 'totalCount'
          },
          {
            text: '已生成',
            value: '2',
            countText: 'generatedCount'
          },
          {
            text: '已揽收',
            value: '4',
            countText: 'collectedCount'
          },
          {
            text: '已交运',
            value: '5',
            countText: 'shippedCount'
          },
          {
            text: '已出库',
            value: '3',
            countText: 'outWarehouseCount'
          },
          {
            text: '退单',
            value: '9',
            countText: 'chargebackCount'
          },
          {
            text: '下单失败',
            value: '7',
            countText: 'failCount'
          },
          {
            text: '已妥投',
            value: '6',
            countText: 'deliveredCount'
          },
          {
            text: '拦截成功',
            value: '8',
            countText: 'interceptedCount'
          },
          {
            text: '草稿',
            value: '1',
            countText: 'draftCount'
          }
        ],
        keyNumber: 0,
        logisticsTrajectory: [],
        currentId: '',
        checked: false
      }
    },
    created() {
      // this.getSuperFieldList();
      document.getElementById('app').addEventListener('click', () => {
        this.currentId = '';
      })
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
      importBill: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importBill}`;
      },
    },
    beforeDestroy(){
      document.getElementById('app').removeEventListener('click', () => {
        this.currentId = '';
      })
    },
    watch: {
      dataSource: {
        handler(val){
          this.getGroupCount();
        }
      }
    },
    methods: {
      moment,
      // initDictConfig(){
      // },
      selectRowData(record,index){
        const that = this
        return {
          on:{
            dblclick:() => {
              // this.handleDetail(record)
            }
          }
        }
      },
      changeTab(index){
        this.queryParam={
          ...this.queryParam,
          waybillStatus: index
        }
        this.searchQuery()
      },
      getGroupCount(){
        getAction(this.url.queryWaybillGroupCount, this.queryParam).then((res) => {
          if(res.success && res.result){
            //获取全部数量
            let valueList = Object.values(res.result);
            res.result.totalCount = valueList.reduce((prev, cur) => {
              return prev + +cur;
            }, 0)
            this.sortList = this.sortList.map(item => {
              if(item.text.indexOf('（') > -1){
                item.text = item.text.split('（')[0];
              }
              return {
                ...item,
                text: `${item.text}（${res.result?.[item.countText] || 0}）`
              }
            })
          }
        })
      },
      handlePrint(record){
        this.loading = true;
        getAction(this.url.previewLabel, {id: record.id}).then((res) => {
          if(res.success){
            const base64Url = `data:application/pdf;base64,${res.message}`;
            var binary = atob(base64Url.split(',')[1]);
            var array = [];
            for (var i = 0; i < binary.length; i++) {
              array.push(binary.charCodeAt(i));
            }
            var blob = new Blob([new Uint8Array(array)], {type: 'application/pdf'});
            // 创建一个指向Blob对象的URL
            var url = URL.createObjectURL(blob);
            // 打开新页面
            var newWindow = window.open(url, '_blank');
            // 注意：新页面打开后，需要主动释放Blob对象占用的URL
            newWindow.onbeforeunload = function() {
              URL.revokeObjectURL(url);
            };
            newWindow.location.href = url;
          }else{
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.loading = false;
        })
      },
      handleTrajectory(record){
        this.loading = true;
        getAction(this.url.queryTrackInfo, {id: record.id}).then((res) => {
          if(res.success){
            this.logisticsTrajectory = res.result;
            this.currentId = record.id;
          }else{
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.loading = false;
        })
      },
      handleChecked(){
        this.checked = !this.checked;
        if(this.checked){
          this.queryParam.isMyCreated = 1;
        }else{
          this.queryParam.isMyCreated = null;
        }
        this.loadData();
      },
      getColor(record){
        // 草稿: 1
        // 已生成: 2
        // 已出库: 3
        // 已揽收: 4
        // 已交运: 5
        // 已妥投: 6
        // 下单失败: 7
        // 拦截成功: 8
        // 退单: 9
        if(record.waybillStatus === '1'){
          return 'color: #797979';
        }
        if(record.waybillStatus === '9' || record.waybillStatus === '7' || record.waybillStatus === '8'){
          return 'color: red';
        }
        return 'color: #1890FF';
      },
      getColor_(record){
        // 未付款: 1
        // 已预扣: 2
        // 未补扣: 3
        // 退款: 4
        // 已付款: 5
        if(record.settleStatus === '1'){
          return 'color: #797979';
        }
        if(record.settleStatus === '2'){
          return 'color: #009b0f';
        }
        if(record.settleStatus === '3'){
          return 'color: #ff7e14';
        }
        if(record.settleStatus === '4'){
          return 'color: red';
        }
        return 'color: #1890FF';
      },
      handleIntercept(record){
        this.loading = true;
        getAction(this.url.interceptWaybill, {id: record.id}).then((res) => {
          if(res.success){
            this.$message.success(res.message);
            this.loadData();
          }else{
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.loading = false;
        })
      },

      effectCreateTimeChange(){
        this.queryParam.createTime_begin = this.queryParamOther.createTimeRange && this.queryParamOther.createTimeRange[0];
        this.queryParam.createTime_end = this.queryParamOther.createTimeRange && this.queryParamOther.createTimeRange[1];
      },
      printWaybillTimeChange(){
        this.queryParam.printWaybillTime_begin = this.queryParamOther.printWaybillTimeRange && this.queryParamOther.printWaybillTimeRange[0];
        this.queryParam.printWaybillTime_end = this.queryParamOther.printWaybillTimeRange && this.queryParamOther.printWaybillTimeRange[1];
      },
      reconciliationTimeChange(){
        this.queryParam.reconciliationTime_begin = this.queryParamOther.reconciliationTimeRange && this.queryParamOther.reconciliationTimeRange[0];
        this.queryParam.reconciliationTime_end = this.queryParamOther.reconciliationTimeRange && this.queryParamOther.reconciliationTimeRange[1];
      },
      handleEdit_(record){
        this.$refs.modalForm.edit(record);
        this.$refs.modalForm.title = "编辑";
        // 暂时只有草稿态可以编辑(下单失败（未付款、退款中），其中未付款可以编辑)
        this.$refs.modalForm.disableSubmit = (record.waybillStatus === '1' || (record.waybillStatus === '7' && record.settleStatus === '1')) ? false : true;
      },
      searchReset_(){
        //重置页面展示异常问题
        this.keyNumber++;
        this.queryParam = {
          createTime_begin: moment(moment().subtract(1, 'month').startOf('day')).format('YYYY-MM-DD HH:mm:ss'),
          createTime_end: moment(moment().endOf('day')).format('YYYY-MM-DD HH:mm:ss')
        }
        this.loadData(1);
      }
    }
  }
</script>
<style scoped lang="less">
  @import '~@assets/less/common.less';
  .waybill{
    position: relative;
    .trajectory{
      position: absolute;
      left: 130px;
      top: 0;
      border: 1px solid #ddd;
      box-shadow: 0px 0px 10px #ddd;
      border-radius: 4px;
      background-color: #fff;
      padding: 10px;
      text-align: left;
      max-height: 200px;
      overflow-y: auto;
      &>div:not(:first-child){
        margin-top: 10px;
      }
      .time{
        color: #ff5a14;
      }
      .info{
        font-weight: bold;
      }
    }
  }
  .templateSlot{
    text-align: left;
  }
</style>